package com.flower.common.exception;

import com.flower.common.model.Reply;
import com.flower.common.model.ResultEnum;
import com.flower.common.utils.GsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * The type Global exception handler.
 *
 * @author shanks
 * @since 2019 -09-25  16:02
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * Logic exception handler reply.
     *
     * @param e the e
     * @return the reply
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public String logicExceptionHandler(Exception e) {

        Reply reply;
        if (e instanceof LogicException) {
            LogicException logicException = (LogicException) e;
            reply = Reply.builder()
                    .code(logicException.getResultEnum().getCode())
                    .message(logicException.getResultEnum().getMessage())
                    .build();
        } else {
            //如果是系统逻辑异常，不打印
            logger.error("系统异常：" + e.getMessage(), e);
            reply = Reply.builder()
                    .code(ResultEnum.INNER_EXCEPTION.getCode())
                    .message(ResultEnum.INNER_EXCEPTION.getMessage())
                    .build();

        }
        String text = GsonUtil.toJsonString(reply);
        logger.info("返回参数：{}", text);
        return text;
    }
}
